package net.huashitong.zhApp.controller;

import com.sirdc.modules.sys.filter.NodeNewschedulesModel;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.filter.NewProjectsFilter;
import net.huashitong.Project.service.NewProjectsService;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.filter.NodeNewschedulesFilter;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.oversee.entity.GradePoint;
import net.huashitong.oversee.entity.SupervisionTask;
import net.huashitong.oversee.entity.TackTaskLog;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.service.GradePointService;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.oversee.service.TackTaskLogService;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.service.BnpUserService;
import net.huashitong.utils.UtilsTools;
import net.huashitong.zhApp.service.AppReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;

@Controller
@RequestMapping(value = "/zhApp/task")
public class AppTaskController extends BaseCtrl {

    @Autowired
    private NewProjectsService newProjectsService;
    @Autowired
    private NodeNewschedulesService nns;
    @Lazy
    @Autowired
    private AppReportService appReportService;
    @Autowired
    private SupervisionTaskService supervisionTaskService;
    @Autowired
    private TackTaskLogService tackTaskLogService;
    @Autowired
    private BnpUserService bnpUserService;
    @Autowired
    private GradePointService gradePointService;

    /**
     * 待办任务
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryTaskNeedDealWithList", method = RequestMethod.POST)
    public Map<String, Object> queryTaskNeedDealWithList(@RequestBody SupervisionTaskFilter filter) throws ParseException {
        Map<String, Object> resMap = new HashMap<>();
        /**
         * 待办任务
         * 节点部分（业主单位0 经办人提示到网页操作、查看节点情况|业主单位0 责任人查看节点情况）
         * 节点部分（审批部门1 经办人可进行审核操作、查看节点情况|审批部门1 责任人查看节点情况）
         */
        BnpUser user = queryUserAuth(filter.getUserPhone());
        if (ObjectUtils.isBlank(user)) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", "202");
            result.put("message", "无用户权限");
            return result;
        } else {
            String branchType = user.getBranchType();
            String role = user.getRole();
            String flag = branchType + role;
            //责任单位经办人（提示网页上传文件完成节点任务，并查看节点情况）
            NodeNewschedulesFilter nnsFilter = new NodeNewschedulesFilter();
            NewProjectsFilter pf = new NewProjectsFilter();
            if ("0经办人".equals(flag)) {
                pf.setUserId(user.getSysId());
                nnsFilter.setOperatorPhone(filter.getUserPhone());
                nnsFilter.setState("1");
                nnsFilter.setType("2");
//                nnsFilter.setStatus("1");
            } else if ("1经办人".equals(flag)) {
                nnsFilter.setOperatorPhone(filter.getUserPhone());
                nnsFilter.setState("1");
                nnsFilter.setType("2");
//                nnsFilter.setStatus("1");
            } else if ("0责任人".equals(flag)) {
                nnsFilter.setResUserPhone(filter.getUserPhone());
                nnsFilter.setState("1");
                nnsFilter.setType("2");
//                nnsFilter.setStatus("1");
            } else {
                nnsFilter.setResUserPhone(filter.getUserPhone());
                nnsFilter.setState("1");
                nnsFilter.setType("2");
//                nnsFilter.setStatus("1");
            }
            List<NodeNewschedules> nodeList = nns.queryNoPageByFilter(nnsFilter);
            List<NewProjects> projectsList = newProjectsService.getProjectInfo3(pf);
            List<Map<String, Object>> resList = new ArrayList<>();
            for (NewProjects project : projectsList) {
                Map<String, Object> map = new HashMap<>();
                map.put("projectId", project.getSysId());
                map.put("projectName", project.getName());
                List<NodeNewschedulesModel> nodes = new ArrayList();
                for (NodeNewschedules node : nodeList) {
                    if (project.getSysId().equals(node.getProjectId())) {
                        List<NodeNewschedulesModel> nodeModel = appReportService.getNodeDetailByProjectId(project.getSysId(), node.getNodeIds());
                        for (NodeNewschedulesModel model : nodeModel) {
                            if (node.getNodeId().equals(model.getNodeId())) {
                                //审批部门要有相应的小节点
                                if ("0".equals(user.getBranchType())) {
                                    nodes.add(model);
                                }
                            }
                        }
                        //审批部门要有全部的小节点
                        if ("1".equals(user.getBranchType())) {
                            nodes.addAll(nodeModel);
                        }
//                        nodes.addAll(nodeModel);
                    }
                }
                if (nodes.size() > 0) {
                    map.put("dealWithNodes", nodes);
                    resList.add(map);
                }
            }
            resMap.put("code", "200");
            resMap.put("message", "获取成功");
            resMap.put("userAuth", user);
            resMap.put("data", resList);
            return resMap;
        }
    }

    /**
     * 查看攻坚过程日志
     */
    @ResponseBody
    @RequestMapping(value = "/readLog/{id}", method = RequestMethod.GET)
    public Map<String, Object> readLog(@PathVariable String id) {
        Map<String, Object> resMap = new HashMap<>();
        List<TackTaskLog> logs = tackTaskLogService.queryTackLogByTaskId(id);
        resMap.put("code", "200");
        resMap.put("message", "获取成功");
        resMap.put("data", logs);
        return resMap;
    }


    /**
     * 办结攻坚任务
     *
     * @param filter userPhone:手机号码
     *               record:反馈记录
     *               tackFlag:1暂不办结，只提交反馈    2立即办结（非必填）
     *               sysId:攻坚任务ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/finishTack", method = RequestMethod.POST)
    public Map<String, Object> finishTack(@RequestBody SupervisionTaskFilter filter) {
        Map<String, Object> resMap = new HashMap<>();
        BnpUser user = queryUserAuth(filter.getUserPhone());
        if (ObjectUtils.isBlank(user)) {
            resMap.put("code", "202");
            resMap.put("message", "无用户权限");
            return resMap;
        } else {
            String taskId = filter.getSysId();
            SupervisionTask task = supervisionTaskService.getById(taskId);
            TackTaskLog log = new TackTaskLog();
            log.setRecord(filter.getRecord());
            log.setNodeSysId(task.getNodeSysId());
            log.setTaskId(taskId);
            if (ObjectUtils.isNotBlank(user)) {
                log.setRecordPerson(user.getName());
                log.setRecordPersonSysId(user.getSysId());
            }
            if (StringUtils.isNotBlank(filter.getTaxproof())) {
                log.setTaxproof(filter.getTaxproof());
            }
            tackTaskLogService.save(log);
            if (StringUtils.isNotBlank(filter.getTackFlag())) {
                task.setTackFlag(filter.getTackFlag());
            }
            supervisionTaskService.update(task);
            resMap.put("code", "200");
            resMap.put("message", "更新成功");
            return resMap;
        }
    }


    /**
     * 审核攻坚
     * tackFlag 3通过 1不通过（必填） sysId: 攻坚任务id （必填）;
     * approvalTackText 审核备注
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/approval", method = RequestMethod.POST)
    public Map<String, Object> approval(@RequestBody SupervisionTaskFilter filter) throws ParseException {
        Map<String, Object> resMap = new HashMap<>();
        String taskId = filter.getSysId();
        SupervisionTask task = supervisionTaskService.getById(taskId);
        if (StringUtils.isNotBlank(filter.getTackFlag())) {
            task.setTackFlag(filter.getTackFlag());

            //查询分管领导
            String projectId = task.getProjectId();
            NewProjects project = newProjectsService.getById(projectId);
            String resUser = project.getResUser();          //分管领导
            String resPhone = project.getResPhone();        //分管领导手机号
            BnpUser fenguanUser = bnpUserService.getBnpUserByPhoneAndName(resPhone, resUser);
            String fenguanUserId = "null";
            String fenguanUserName = "null";
            String fenguanUserBranch = "null";
            if (ObjectUtils.isNotBlank(fenguanUser)) {
                fenguanUserId = fenguanUser.getSysId();
                fenguanUserName = fenguanUser.getName();
                fenguanUserBranch = fenguanUser.getBranch();
            }

            //审核通过
            if ("3".equals(filter.getTackFlag())) {
                List<TackTaskLog> logs = tackTaskLogService.queryTackLogByTaskId(taskId);
                //攻坚完成  督查结果设置--1
                task.setTaskResult("1");
                task.setRespResult("1");
                task.setSupervisionResult("1");
                //攻坚完成设置实际完成时间
                if (logs.size() > 0) {
                    if (StringUtils.isNotBlank(task.getFinishTackDate())) {
                        task.setEndDate(task.getFinishTackDate());
                    } else {
                        task.setEndDate(logs.get(0).getCreateDate().replace("-", ""));
                    }
                } else {
                    //特殊情况
                    task.setEndDate(UtilsTools.getCurrentDate());
                }
                //保存办结时间到任务表里面
                task.setFinishTackDate(task.getEndDate());
                //保存审核时间到任务表里面
                task.setApprovalTackDate(UtilsTools.getCurrentDate());
                task.setApprovalTackText(filter.getApprovalTackText());
                //设置及时完成率
                Date EndDate = UtilsTools.StringToDate(task.getPlanEndDate());  //计划完成时间
                Date currentDate = UtilsTools.StringToDate(task.getEndDate());  //办结时间（实际完成时间）
                int flag = EndDate.compareTo(currentDate); //计划结束时间和当前时间比较。是否到期。

                //审核通过将得分记录到绩效得分表里面去(考核分管领导)
                GradePoint gradePoint = new GradePoint();
                gradePoint.setCheckObjectId(fenguanUserId);
                gradePoint.setCheckObject(fenguanUserName);
                gradePoint.setTaskName(task.getTaskName());
                gradePoint.setTaskId(task.getSysId());
                gradePoint.setTaskContent(task.getTaskContent());
                gradePoint.setResDept(fenguanUserBranch);
                gradePoint.setCheckType("攻坚任务");
                if (flag == 0) {
                    //计划结束当天完成
                    task.setTackPercent("80.0");
                    gradePoint.setSoucre("10.0");
                } else if (flag < 0) {
                    //超时完成
                    task.setTackPercent("60.0");
                    gradePoint.setSoucre("10.0");
                } else {
                    //计划时间完成
                    task.setTackPercent("100.0");
                    gradePoint.setSoucre("10.0");
                }
                gradePointService.save(gradePoint);
            } else {
                GradePoint gradePoint = new GradePoint();
                gradePoint.setCheckObjectId(fenguanUserId);
                gradePoint.setCheckObject(fenguanUserName);
                gradePoint.setTaskName(task.getTaskName());
                gradePoint.setTaskId(task.getSysId());
                gradePoint.setTaskContent(task.getTaskContent());
                gradePoint.setResDept(fenguanUserBranch);
                gradePoint.setCheckType("攻坚任务");
                gradePoint.setSoucre("0.0");
                gradePointService.save(gradePoint);
            }
        }
        supervisionTaskService.update(task);
        resMap.put("code", "200");
        resMap.put("message", "更新成功");
        return resMap;
    }


}
